package com.pro.framework.spring.util;

import com.pro.framework.api.model.FrameworkException;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Getter
public abstract class BaseServiceFactory<KEY, SERVICE> {

    private final Map<KEY, SERVICE> serviceMap = new HashMap<>();

    @Autowired
    public void register(List<SERVICE> services) {
        for (SERVICE service : services) {
            KEY key = getKeyFromService(service);
            if (serviceMap.containsKey(key)) {
                log.warn("键 [{}] 的 SERVICE 已被覆盖", key);
            }
            serviceMap.put(key, service);
        }
    }

    public SERVICE getService(KEY key) {
        return getService(key, true);
    }

    protected SERVICE getService(KEY key, boolean nullThrow) {
        SERVICE service = serviceMap.get(key);
        if (nullThrow && service == null) {
            throw new FrameworkException("未找到键对应的服务__", key, getClass());
        }
        return service;
    }

    /**
     * 抽象方法，子类需要实现如何从 SERVICE 中提取 KEY
     * @param service 服务实例
     * @return 对应的键
     */
    protected abstract KEY getKeyFromService(SERVICE service);
}
